package com.it.base.core.system.dict.service.impl;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.base.common.view.PageResult;
import com.it.base.core.system.dict.mapper.SysDictDataMapper;
import com.it.base.core.system.dict.model.entity.SysDictData;
import com.it.base.core.system.dict.model.from.SysDictDataSelectPageListFormDTO;
import com.it.base.core.system.dict.model.from.SysDictDataValidatorFormDTO;
import com.it.base.core.system.dict.service.ISysDictDataService;
import com.it.base.support.string.StringUtil;

@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService {

	@Autowired
	private SysDictDataMapper sysDictDataMapper;

	@Override
	public PageResult<SysDictData> selectPageList(SysDictDataSelectPageListFormDTO sysDictDataSelectPageListFormDTO) {
		QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();

		if (StringUtil.isNotBlank(sysDictDataSelectPageListFormDTO.getType())) {
			queryWrapper.lambda().eq(SysDictData::getType, sysDictDataSelectPageListFormDTO.getType());
		}

		if (StringUtil.isNotBlank(sysDictDataSelectPageListFormDTO.getLabel())) {
			queryWrapper.lambda().likeRight(SysDictData::getLabel, sysDictDataSelectPageListFormDTO.getLabel());
		}

		if (sysDictDataSelectPageListFormDTO.getStatus() != null) {
			queryWrapper.lambda().eq(SysDictData::getStatus, sysDictDataSelectPageListFormDTO.getStatus());
		}

		queryWrapper.lambda().orderByAsc(SysDictData::getSort);
		IPage<SysDictData> page = sysDictDataMapper.selectPage(new Page<>(sysDictDataSelectPageListFormDTO.getPageNo(),
				sysDictDataSelectPageListFormDTO.getPageSize()), queryWrapper);
		return new PageResult<>(page.getTotal(), page.getRecords());
	}

	@Override
	public boolean validatorExist(@Valid SysDictDataValidatorFormDTO sysDictDataValidatorFormDTO) {
		QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SysDictData::getType, sysDictDataValidatorFormDTO.getType());
		queryWrapper.lambda().eq(SysDictData::getValue, sysDictDataValidatorFormDTO.getValue());

		if (StringUtil.isNotBlank(sysDictDataValidatorFormDTO.getId())) {
			queryWrapper.lambda().ne(SysDictData::getId, sysDictDataValidatorFormDTO.getId());
		}

		return this.count(queryWrapper) > 0;
	}

}
